<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRolesDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="roleList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <!-- 插槽具有获取当前组件下的所有值 -->
          <template v-slot:default="scope">
            <!-- (v-slot:default="scope")==(slot-scope="scope") -->
            <!-- 用pre美化数据 -->
            <!-- 栅格布局 -->
            <el-row
              :gutter="24"
              v-for="(item1, index) in scope.row.children"
              :key="item1.id"
              :class="[
                'borderbottom',
                index === 0 ? 'bordertop' : '',
                'vcenter',
              ]"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightByid(scope.row, item1.id)"
                  >{{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限和三级 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, index) in item1.children"
                  :key="item2.id"
                  :class="[index === 0 ? '' : 'bordertop', 'vcenter']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightByid(scope.row, item2.id)"
                    >
                      {{ item2.authName }}</el-tag
                    ><i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级 -->
                  <el-col :span="18">
                    <el-tag
                      closable
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      @close="removeRightByid(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{ scope.row }}</pre> -->
          </template>
        </el-table-column>
        <!-- 添加索引 -->
        <!-- 添加#有这个会让表格没对齐 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="RolesEidtDialogVisible(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeRoleuserByid(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetDialogVisible(scope.row)"
              @close="setRightDialogVisibleClose"
              >分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色提示框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addRolesDialogVisible"
      width="50%"
      @close="addRolesFromClose"
    >
      <!-- 主体区域 -->
      <el-form
        :model="addRolesForm"
        :rules="addRolesFormRules"
        ref="addRolesFormRef"
        label-width="80px"
        status-icon
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRolesNewUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色提示框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="eidtRolesDialogVisible"
      width="50%"
      @close="eidtRolesFromClose"
    >
      <!-- 主体区域 -->
      <el-form
        :model="eidtRolesForm"
        :rules="eidtRolesFormRules"
        ref="eidtRolesFormRef"
        label-width="80px"
        status-icon
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="eidtRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="eidtRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="eidtRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="eidtRolesNewUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限提示框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="SetRightdialogVisible"
      width="50%"
      @close="setRightDialogVisibleClose"
    >
      <!-- 通过props属性获取值 -->
      <!-- 每个树节点用来作为唯一标识的属性，整棵树应该是唯一的 id从rightsTreeList获取的-->
      <el-tree
        :data="rightsTreeList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defkeys"
        ref="refTree"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="SetRightdialogVisible = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="allotRights"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 权限列表
      roleList: [],
      // 添加角色提示框的显示状态
      addRolesDialogVisible: false,
      // 修改角色提示框的显示状态
      eidtRolesDialogVisible: false,
      // 配角色权限提示框的显示状态
      SetRightdialogVisible: false,
      // 添加角色表单数据
      addRolesForm: {
        roleName: '',
        roleDesc: ''
      },
      //   修改角色
      eidtRolesForm: {},
      //   树状权限列表数据
      rightsTreeList: [],
      //   tree对象
      treeProps: {
        // 小集合名
        label: 'authName',
        children: 'children'
      },
      //   默认选中的节点ID值数组
      defkeys: [],
      // 当前即将分配的id
      roleID: '',
      // 验证规则
      addRolesFormRules: {
        roleName: [
          {
            required: true,
            message: '请输入角色名称',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          {
            required: true,
            message: '请输入角色描述',
            trigger: 'blur'
          }
        ]
      },
      eidtRolesFormRules: {
        roleName: [
          {
            required: true,
            message: '请输入角色名称',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          {
            required: true,
            message: '请输入角色描述',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created () {
    this.getRoleList()
  },
  methods: {
    async getRoleList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) { return this.$message.error('获取角色列表失败') }
      this.$message.success('获取角色列表成功')
      this.roleList = res.data
      //   console.log(res);
    },
    // 添加
    addRolesFromClose () {
      // 给获取的实例对象添加一个重置的方法
      this.$refs.addRolesFormRef.resetFields()
    },
    // 添加角色的预验证
    addRolesNewUser () {
      this.$refs.addRolesFormRef.validate(async (valid) => {
        // console.log(valid);
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addRolesForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success('添加用户成功')
        //  隐藏对话框
        this.addRolesDialogVisible = false
        this.getRoleList()
      })
    },
    // 获取角色信息
    async RolesEidtDialogVisible (rolesid) {
      this.eidtRolesDialogVisible = true
      const { data: res } = await this.$http.get(`roles/${rolesid}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success('获取角色信息成功')
      this.eidtRolesForm = res.data
      //   console.log(this.eidtRolesForm)
    },
    eidtRolesFromClose () {
      // 给获取的实例对象添加一个重置的方法
      this.$refs.eidtRolesFormRef.resetFields()
    },
    // 编辑的预验证
    eidtRolesNewUser () {
      this.$refs.eidtRolesFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'roles/' + this.eidtRolesForm.roleId,
          {
            roleName: this.eidtRolesForm.roleName,
            roleDesc: this.eidtRolesForm.roleDesc
          }
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success('编辑角色信息成功')
        this.eidtRolesDialogVisible = false
        // 重新获取角色列表
        this.getRoleList()
      })
    },
    // 删除提示
    async removeRoleuserByid (rolesid) {
      //  console.log(userid)
      const conformResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      // console.log(conformResult)
      // 如果用户确认删除就是返回字符串confirm
      // 如果用户取消删除返回cancel
      if (conformResult !== 'confirm') {
        return this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }
      const { data: res } = await this.$http.delete(`roles/${rolesid}`)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败')
      this.$message.success('删除用户成功')
      // 重新获取角色列表
      this.getRoleList()
    },
    // 删除权限
    async removeRightByid (role, rightId) {
      const conformResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (conformResult !== 'confirm') {
        return this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) return this.$message.error('删除指定失败')
      //   this.$message.success("删除指定权限成功");
      //   刷新表全部刷新很烦
      // this.getRoleList();
      // 重新赋值双向绑定666
      role.children = res.data
    },
    // 分配权限弹出框
    async showSetDialogVisible (role) {
      // 获取权限树状图数据
      // 向分配权限上传一个值
      this.roleID = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) { return this.$message.error('获取权限树状图失败') }
      // this.$message.success("获取权限列表成功");
      this.rightsTreeList = res.data
      //   console.log(this.rightsTreeList);
      //   递归获取三级节点
      this.getLeftKeys(role, this.defkeys)
      this.SetRightdialogVisible = true
    },
    // 通过递归的形式 ，获取角色下的搜友三级权限并保存在defkeys数组
    getLeftKeys (node, arr) {
      // 如果当前node节点不包含children属性就为三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      //   递归
      node.children.forEach((item) => this.getLeftKeys(item, arr))
    },
    // 监听分配权限的关闭权限解决小bug
    setRightDialogVisibleClose () {
      this.defkeys = []
    },
    // 点击为角色分配权限
    async  allotRights () {
      const keys = [
        // 通过引用获取选中的节点值...变量.依次获取值
        ...this.$refs.refTree
          .getCheckedKeys(),
        ...this.$refs.refTree
          .getHalfCheckedKeys()
      ]
      // console.log(keys)
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleID}/rights`, { rids: idStr })
      if (res.meta.status !== 200) { return this.$message.error('权限更新失败') }
      this.$message.success('权限更新成功')
      this.SetRightdialogVisible = false
      this.getRoleList()
    }
  }
}
</script>
// 直接引用报错手打没事
<style Lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bordertop {
  border-top: 1px solid #eee;
}

.borderbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
